<?php

namespace App\Console\Commands;

use App\Models\ZPituitaryUser;
use App\Models\ZZMed\ZUser;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DelUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'del:user';


    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '删除指定表的数据便于清理数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $cells = ZPituitaryUser::query()->from('z_pituitary_user_need_delete')
            ->selectRaw('cell')
            ->get()->toArray();

        if ($cells) {

            $cellArr = array_column($cells, 'cell');

            ## 清空需要删除的数据
            DB::table('z_pituitary_user_need_delete')->whereIn('cell', $cellArr)->delete();

            $userIds = ZUser::query()->selectRaw('id')->whereIn('cell', $cellArr)->get()->toArray();

            $userIdArr = array_column($userIds, 'id');

            ## 问 卷
            DB::table('z_pituitary_answer')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_answer_log')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_complete')->whereIn('user_id', $userIdArr)->delete();

            ## 用 药
            DB::table('z_pituitary_manage_drugs')->whereIn('user_id', $userIdArr)->delete();

            ## 随访+标签+联系记录
            DB::table('z_pituitary_patients_notice')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_patients_tag')->where('patient_id', $userIdArr)->delete();
            DB::table('z_pituitary_upload')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_user_contact_records')->whereIn('user_id', $userIdArr)->delete();

            ## 入组就诊
            DB::table('z_pituitary_user')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_visit_level')->whereIn('user_id', $userIdArr)->delete();
            DB::table('z_pituitary_visit_records')->whereIn('user_id', $userIdArr)->delete();

            ## 类 型
            DB::table('z_pituitary_user_type')->whereIn('user_id', $userIdArr)->delete();

            Log::info("垂体系统删除用户程序运行完成,删除用户ids 为", $userIdArr);
        }
        echo 'success';

    }
}
